<!-- 单图片上传控件 -->
<template>
  <a-upload
    list-type="picture"
    action="/"
    @progress="onProgress"
    :show-file-list="false"
    @change="onChange"
    @success="success"
    @error="error"
    :auto-upload="false"
    :tip="tip"
    :disabled="disabled"
    image-preview
  >
    <template #upload-button>
      <div>
        <div
          class="arco-upload-list-picture custom-upload-avatar"
          :class="`arco-upload-list-item${
            currFile && currFile.status === 'error'
              ? ' arco-upload-list-item-error'
              : ''
          }`"
          v-if="currFile.url !== ''"
        >
          <a-tooltip :content="currFile.name">
            <div>
              <img :src="currFile.url" :alt="currFile.name" />
              <div class="arco-upload-list-picture-mask">
                <IconEdit />
              </div>
              <a-progress
                v-if="currFile.status === 'uploading' && currFile.percent < 100"
                :percent="currFile.percent"
                type="circle"
                size="mini"
                :style="{
                  position: 'absolute',
                  left: '50%',
                  top: '50%',
                  transform: 'translateX(-50%) translateY(-50%)'
                }"
              />
            </div>
          </a-tooltip>
        </div>
        <div class="arco-upload-picture-card" v-else>
          <div class="arco-upload-picture-card-text">
            <IconPlus />
            <div style="margin-top: 10px; font-weight: 600">点击上传图片</div>
          </div>
        </div>
      </div>
    </template>
  </a-upload>
</template>

<script lang="ts" setup>
import { PostFile } from '@/apis/management/base';
import { Message } from '@arco-design/web-vue';

const props = withDefaults(
  defineProps<{
    props: { [propName: string]: any };
    name?: string;
    required?: boolean;
    oneValue: any;
    disabled?: boolean;
    regex?: {
      [name: string]: {
        role: any;
        name: any;
      };
    };
  }>(),
  {}
);
const emit = defineEmits(['update:oneValue']);

// 储存当前图片
let currFile = ref<any>({
  uid: '-1',
  name: '',
  url: ''
});

const modelValue = computed({
  get: () => {
    return props.oneValue;
  },
  set: (val) => {
    emit('update:oneValue', val);
  }
});

// watch(
//   () => props.oneValue,
//   (newVal: string) => {
//     console.log('==============asdasd');
//     console.log(newVal);
//     console.log('====================================');
//     // currFile.value = JSON.parse(newVal);
//     if (newVal[0] !== '' && newVal !== undefined) {
//       currFile.value = JSON.parse(newVal);
//     } else {
//       currFile.value = {
//         uid: '-1',
//         name: '',
//         url: ''
//       };
//     }
//   },
//   {
//     // immediate: true
//   }
// );

onMounted(() => {
  if (
    modelValue.value !== undefined &&
    modelValue.value[0] !== '' &&
    modelValue.value
  )
    currFile.value = JSON.parse(modelValue.value);
});

//复制一份props
const getProps = computed(() => {
  return props.props;
});

const tip = `只能上传一张图片`;

// 文件上传
const onChange = async (_, currentFile: any) => {
  try {
    currFile.value = {
      ...currentFile
      // url: URL.createObjectURL(currentFile.file),
    };
    console.log(currFile.value);

    let temp = new FormData();
    temp.append('data', currentFile.file);
    console.log(temp);
    const url = await PostFile(temp);

    modelValue.value = JSON.stringify({
      url,
      uid: currFile.value.uid,
      name: currFile.value.name
    });
    // let index = url.lastIndexOf('\/');
    // modelValue.value = url.substring(index + 1, url.length);
  } catch (error: unknown) {
    console.log(error);
  }
};
const onProgress = (currentFile: any) => {
  currFile.value = currentFile;
};

// 成功时候调用
const success = (fileItem: any) => {
  Message.success('上传文件成功！');
};

// 失败的时候调用
const error = (fileItem: any) => {
  Message.error('上传文件失败，请重新上传！ ');
};
</script>

<style scoped lang="less"></style>
